package com.asggo.g21.service;

import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

import io.github.bucket4j.Bucket;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2024/2/19 16:16
 */
@SpringBootTest
class Bucket4jServiceTests {

  @Autowired
  Bucket4jService bucket4jService;

  @Test
  void tryConsume() {
    Awaitility.setDefaultTimeout(5, TimeUnit.MINUTES);
    assertThat(bucket4jService).isNotNull();

    String apiKey = "bucket4j";

    final Bucket bucket = bucket4jService.resolveBucketHazelcast(apiKey);
    for (int i = 0; i < 1000; ++i) {
      System.out.println("bucket.getAvailableTokens() -》" + bucket.getAvailableTokens());
      if (bucket.tryConsume(1)) {
        System.out.println(i + 1);
      } else {
        System.out.println("当前时间：" + LocalDateTime.now());
        System.out.println("bucket.getAvailableTokens() -》" + bucket.getAvailableTokens());
        await().until(() -> bucket.tryConsume(1));
      }
    }

  }
}
